import { PlusOutlined } from '@ant-design/icons'
import { Empty, Button } from 'antd'
import Table, { ColumnsType } from 'antd/es/table'
import React, { useEffect, useRef, useState } from 'react'
import { ITableData } from '../types'
import './EditTable.less'
interface IProps {
  tableData: any[]
  settableData: React.Dispatch<React.SetStateAction<any[]>>
  columns: ColumnsType<any>
  showAddBtn?: boolean
}
export default function EditTable(props: IProps) {
  const tableRef = useRef<HTMLDivElement>(null)
  const [isEditing, setIsEditing] = useState(false)
  const { tableData, settableData } = props
  const handleCellClick = (event: any) => {
    if (!props.showAddBtn) return
    if (
      Object.prototype.toString.call(event.target) === '[object SVGSVGElement]' ||
      Object.prototype.toString.call(event.target) === '[object SVGPathElement]'
    ) {
      return
    }
    setIsEditing(true)
  }
  const handleClickOutside = (event: any) => {
    if (!props.showAddBtn) return
    if (tableRef.current && typeof event?.target?.className == 'string') {
      if (
        !tableRef.current.contains(event.target) &&
        event?.target?.className?.indexOf('ant-select') == -1 &&
        event?.target?.className?.indexOf('spec_input_drop_down') == -1
      ) {
        const clickPath = event.path || (event.composedPath && event.composedPath())
        if (!clickPath.includes(tableRef.current)) {
          if (isEditing) {
            setIsEditing(false)
            settableData([...tableData])
          }
        }
      }
    }
  }
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [tableData])
  const addData = () => {
    tableData.splice(0, 0, {
      tempId: new Date().getTime(),
    })
    settableData([...tableData])
  }
  return (
    <div ref={tableRef} className="quotation_table_container" onClick={handleCellClick}>
      <Table
        bordered
        rowKey="tempId"
        dataSource={tableData}
        columns={props.columns}
        pagination={false}
        locale={{
          emptyText: (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}>
              {props?.showAddBtn && <Button type="primary" icon={<PlusOutlined />} size="small" onClick={addData} />}
            </Empty>
          ),
        }}
        scroll={{
          x: 960,
          y: 300,
        }}
      />
    </div>
  )
}
